<?xml version="1.0" encoding="utf-8"?>
<Content xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="urn:blueonionsoftware-com:bloget:runtime:data">
  <text>Here are the notes I took during our recent three-day training class for .NET and C#


C# Training Class

CodeDom Model â€“ Used to generate/compile/invoke C# code on the fly, etc.
Â·	Collections objects containing namespaces, imports, types &amp; members
Â·	Members (represents a C# [user-defined?] type/class ?) consist of methods, properties, events and fields
Â·	CodeCompileUnit â€“ top-level class to be used as your starting point.
Â·	CodeTypeDeclaration, CodeEntryPointMethod, CodeMethodInvokeExpression, CodePrimitiveExpression, 

CodeTypeReferenceExpression, CodeArgumentReferenceExpression, etc. classes.
Â·	Microsoft.CSharp.CSharpCodeProvider
Â·	CodeGeneratorOptions, CompilerParameters, CodeDomProvider
Â·	Code can be generated (i.e. a .cs file) then compiled, or compiled directly from the model.
Â·	Generated assembly can even be written to a memory stream instead of a disk file, then loaded and run from there.

AppDomain â€“ used for loading/running assemblies within an existing process.  (Among other things?)
Â·	ExecuteAssembly()
Â·	CorpubPublish, ICorPublishProcess
Â·	Managed code will not shut the process down as long as any managed threads are still running.
Â·	Can specify a private bin path to search for additional assemblies to be loaded.
Pre-JITâ€™ed assemblies must reside in the GAC.  Original assembly must still be available for metadata, etc.
If not pre-JITâ€™ed, assembly code is JITâ€™ed on a method-by-method basis.  If some methods are never called they will never be JITâ€™ed.

REFLECTOR â€“ Must-use utility.

FxCOP â€“ Will detect deprecated method usage (among other things ?)

[Obsolete()] â€“ Attribute that tags (methods?) as obsolete.  Prints out warning, but does not cause compiler to fail.  Takes an optional string parameter for an informational message, plus a second optional parameter that generates a compiler error instead of a warning if set to true.

Add Reference â€“ All references listed are not written to the assemblyâ€™s manifest unless theyâ€™re actually invoked from that assembly.

CLR Loading of assemblies your assembly uses:
Â·	If assembly is strong-named CLR will look in GAC first.  NOTE: Stay out of the GAC!  Should only be used by Microsoft.
Â·	Then look in local directory
Â·	Then look for subfolder with same name as assembly
Â·	If still not found, look for config file that specifies additional locations
o	Only EXEs and web apps can have a .config file (not DLLs.)
o	Can contain a semicolon-delimited list of subdirectories (must be subdirectories under folder in which calling assembly resides) to be used as a path for finding the other assemblies.
o	Can also contain application-specific data (via System.Configuration.ConfigurationSettings.AppSettings collection.)
&lt;pre&gt;
&amp;lt;configuration&amp;gt;
	&amp;lt;appsettings&amp;gt;
		&amp;lt;add key=â€?Nameâ€? value=â€?Davidâ€? /&amp;gt;
	&amp;lt;/add&amp;gt;&amp;lt;/appsettings&amp;gt;
	&amp;lt;runtime&amp;gt;&amp;lt;figuration&amp;gt;
&lt;/pre&gt;
Strong-naming can be used to ensure only a certain version of your assembly can be invoked by a given caller.

Garbage Collection
Â·	Class == Reference Type, Struct == Value Type
Â·	Reference types are always created on the heap.
Â·	Value types are created on the stack, unless theyâ€™re part of a class, in which case theyâ€™re inlineâ€™d
Â·	Value types are passed by value
Â·	Need to be boxed/unboxed to convert to/from reference type.  This is an expensive operation, so keep use of value types to a minimum.
Â·	An object can be garbage collected only when the stack frame containing the final reference to that object has been disposed.
&lt;pre&gt;
void foo()
{
	{
	String s = â€?some stringâ€?;
	}
}	// Last reference removed here, not on line above.
&lt;/pre&gt;

Â·	Finalize() method == ~ClassName( )
Â·	Very expensive for the CLR to detect the presence of a Finalize() method on an instance of an object, and to call it.
Â·	Garbage collection occurs on a separate thread from yours.  The GC will suspend all threads in that AppDomain in order to perform a collection cycle.
Â·	Need to implement IDisposable interface to dispose of objectâ€™s resource when requested (by caller ?).
o	VS .NET creates Dispose() method stub for this.
o	Dispose() method needs to do the same cleanup as Finalize(), then call GC.SuppressFinalize(this) to prevent Finalize() method from being called.
o	Make Dispose() so that it only gets executed once.  E.g. use a private bool variable to make sure weâ€™re not already disposed.
o	Throw ObjectDisposedException if call tries to do anything with your object after itâ€™s been disposed.
Â·	Avoid implementing Finalize()/Dispose() unless absolutely necessary.  Donâ€™t implement one but not the other.
Â·	Encourage users of your class to call your Dispose() method (when appropriate/as soon as possible) so that any unmanaged resources your class might use will be released ASAP (instead of waiting for a GC cycle.)
 
Day Two

using keyword â€“ Has three overloads:
Â·	classic using System.Console, etc.
Â·	alias: using X = System.Console
(â€˜Xâ€™ can now be used instead of typing â€œSystem.Consoleâ€?)
Â·	Third way: create a â€˜usingâ€™ block of code:
&lt;pre&gt;
using (m)
{
    m.DoesSomething()
}
&lt;/pre&gt;
Only for IDisposable objects; calls Dispose() method when using block goes out of scope.  Compiler will automatically generate a try..finally block and call Dispose() in the finally block.
NOTE: Compiler will still let you use â€˜mâ€™ after leaving the using block, even though â€˜mâ€™ has been disposed.  Donâ€™t do this.  A better way: using (MyObj m = new MyObj)

Think of C# as a â€œscripting language for generating IL code patterns.â€?

lock keyword â€“ lets you add simple synchronization.
Â·	Generates calls to System.Threading.Monitor class (critical section)
Â·	lock( this ) to get/set object data
Â·	lock( typeof(MyClass) ) to get/set class static data

For more complex synchronization, use the Event, Mutex or Semephore classes.

System.Threading.Interlocked class â€“ Has methods for incrementing, decrementing or exchanging values.  More efficient than using the lock keyword.

Another class: ReaderWriterLock

When using string indexers (i.e. getting named properties from XmlElement, etc.) donâ€™t use string literals in your code to index, create string constants and use these instead.  Typos will be caught by the compiler this way.

Reflection
Â·	.NET assemblies are comprised of three parts: manifest, metadata and IL code.
Â·	Assembly.GetExecutingAssembly().Get*
Â·	Assembly.Load()
Â·	AssemblyName.GetAssemblyName()
Â·	System.Type object â€“ class-wide singleton for all defined types/classes.  If a.GetType() == b.GetType() then a and b are objects of the same type.
Â·	PropertyInfo, MethodInfo et. al.
Â·	Consider loading assemblies into a separate AppDomain; the assemblies will be unloaded when you dispose of the AppDomain.
Â·	C++-style casting only necessary for value types; use as keyword for reference types instead.
Â·	System.Attribute â€“ can derive your class from this to define your own attributes (a la â€œobsoleteâ€? attribute.)  

AttributeUsage attribute.

[Serializable] attribute â€“ designates a class can be persisted to media.   Use [NonSerialized] attribute on data members you do not wish to be serialized.
Â·	Use a formatter (BinaryFormatter, SoapFormatter, your own derived class, etc.) to Serialize/Deserialize objects.

Components â€“ Means design environment can host this class (drag/drop onto a design surface [of some other component]) even though it might not have a window or UI.
Â·	Add â€œCategoryâ€? attributes to your componentâ€™s properties so the designer can group your properties appropriately.  Other property attributes, also (Description, etc.)

Console operations are ignored in windows apps.  You can write a windows app that has console operations for diagnostic purposes, then change the application type to â€œConsole Appâ€? and rebuild.  The appâ€™s windows will still function, but in addition you will have a console window that has the diagnostics.

Delegates
Â·	Used to implement observer/observable pattern
Â·	Used for one piece of software to be able to call into another piece of software, without defining a strict interface, etc.
Â·	No need for pre-defined set of methods to call into.
Â·	Delegates are a type-safe mechanism used to reference such a method.
Â·	Classes need to be derived from System.MulticastDelegate (or System.Delegate, but this wonâ€™t be used in userâ€™s C# code.)  MulticastDelegate maintains an InvocationList which is an array of Delegate.
Â·	Construct by passing a â€œpointerâ€? to a method that is defined to be what is expected; canâ€™t pass in just any old method and mess yourself up.
Â·	Compiler generates an Invoke() method with same signature as delegate declaration.
delegate string MyDelegate( int I, char c) generates: string Invoke( int32, char )
Â·	MyDelegate d = new MyDelegate( MyClass.MyStaticMethod );
Â·	d += new MyDelegate( new MyClass().MyNonStaticMethod );
Â·	Invoke all methods in the delegateâ€™s invocation list by calling d();
Â·	There is no documented or guaranteed order in which delegateâ€™s methods are called.  For now it appears to call them in the order in which they were added to the delegate.  Do not write code that depends upon this behavior.
Â·	Invoke() does not catch exceptions; if one of the methods throws any remaining methods in the delegateâ€™s list will not be invoked.
Â·	If your method returns a value the delegate will return the return value from the last method it invoked.  However, thereâ€™s no guaranteed as to which method was invoked last.
Â·	You can manually go through the delegateâ€™s invocation list and invoke each method via DynamicInvoke() or the â€œ()â€? invocation.
Â·	You can asynchronously invoke the delegateâ€™s methods using BeginInvoke() / EndInvoke().  BeginInvoke() is designed to only operate on a single delegate with a single method, so donâ€™t just call your MulticastDelegate-derived classâ€™ BeginInvoke().
Â·	You can call BeginInvoke() specifying a null thread object.  In that case BeginInvoke() will grab a thread from the thread pool (each process [or maybe each AppDomain ?] has a thread pool that starts out with 5-8 threads and expands as needed.)
Â·	Can use asynch delegates to notify you when callback is ended.  Can also call EndInvoke() with return value of BeginInvoke() to see if the method has completed.

Events
Â·	Basically an extension of delegates.  Events are delegates used as Properties.
Â·	Require delegate definition to be declared: event MyDelegate MyEvent;
Â·	If an event is null, it has no methods referenced.
Â·	Add/remove referenced methods via += and -= operators.  You can declare an event much like a Property, declaring â€œaddâ€? and â€œremoveâ€? methods instead of â€œgetâ€? / â€œsetâ€?.  In this way you can write custom add/remove methods.  Beware that in this case you need to declare your own Delegate data member for your event; it wonâ€™t be created automatically by the compiler in this case.

WeakReference class
Â·	Contains a reference to an object to be notified/invoked, but this reference does not prevent the object from being garbage collected.
 
Day Three

Custom Controls
Â·	Microsoft documentation states you must derive your custom control from UserControl.  However, this makes more work to expose functionality/properties/events for your constituent controls.
Â·	Deriving from Control makes it easier to extend functionality of a single control (as opposed to a user control that is composed of a number of other controls.)
Â·	To avoid thread safety issues, control methods should only be called by the thread that created the hosting form.  If some other thread needs to invoke control methods, use Control.Invoke().
Â·	Another way to asynchronously invoke a controlâ€™s methods is via BeginInvoke()/EndInvoke().
Â·	Can use Control.InvokeRequired Property to determine if weâ€™re currently on a different thread.
Managed / unmanaged interop
Â·	Platform Invoke - Lets .NET programs call any DLL-base methods
Â·	/clr switch â€“ Puts native code in its own â€œcompartmentâ€? in your .EXE; the remainder is a .NET assembly.  By default all functions are managed; all classes, structs and interfaces are unmanaged.

ADO.NET
Â·	Abstraction layer for accessing data from a store.
Â·	DataTable â€“ maps to a database table (or subset of a table) as a view
Â·	DataSet â€“ Contains a set of data from one or more DataTables.
Â·	Let business logic access DataTable/DataSet but not any of the â€œProviderâ€? objects (IDbCommand, IDbConnection, IDataAdapter, IDataReader.)
Â·	ADO.NET maintains its own connection pool (so you donâ€™t have to.)
Â·	Use by adding a DataSource Property to one of your components (UI?) that can only be set to an object that:
o	Implements IList/IListSource
o	Is a type safe collection
Â·	(need to check this yourself)

Getting Ready for .NET Framework 2.0 (and C# 2.0)
Â·	Visual Studio 2005
Â·	Hope to be available sometime around Labor Day.
o	Predicates SQL 2005 (â€œYukonâ€?), which itself predicates VS Team System
o	Next comes Indigo Client (next generation of web services / remoting)
o	Next: new version of VS (â€œOrcasâ€?) then new version of Windows (â€œLonghornâ€?.)  Longhorn uses a new UI mechanism called â€œAvalonâ€? which will use XAML.
o	Indigo proper/full blown
Â·	Partial Types â€“ can be defined across multiple source files.  Uses new partial keyword in class declaration.
Â·	Anonymous Methods
Â·	Delegate Inference
Â·	Static Classes
o	Console class will be a static class in C# 2.0.
Â·	Simple custom iterators easier to implement.
Â·	Generics (new CLR feature)
o	class MyGenericClass&amp;lt;t , T2, etc.&amp;gt; {}
o	IL code uses !0, !1, etc. as placeholders for actual types to be used at runtime.
o	Need new collections classes: System.Collections.Generic
o	You should replace all existing usage of ArrayList with List&amp;lt;t&amp;gt;
o	Also think of reworking all classes that use System.Object/object as a placeholder, using a generic type instead.
Â·	DateTimeKind
Â·	TryParse â€“ like Parse, by doesnâ€™t throw an exception
Â·	Nullable Types â€“ declare variables as Nullable&amp;lt;int&amp;gt; x = 0; or int? y = 1;
o	?? operator â€“ returns 1st value if not null, else returns 2nd value.
o	bool? â€“ Can be true, false or null.  Need two new operators for consistency with SQL booleans: â€œ&amp;â€? and â€œ|â€?
Â·	Communication features â€“ Mail, FTP, serial ports
Â·	Networking
Â·	Security
Â·	Certificates
Â·	File and Directory Support
Â·	â€œfriendâ€? Assemblies
	

QUESTIONS:Â·	Can you create apps that run under .NET Framework 1.0, 1.1 and 2.0?  Yes, but don't use any version-specific features.  There will be a Project Setting in VS 2005 that lets you specify the target framework version(s).
</text>
  <last_update>2007-10-04T00:52:26.7570806Z</last_update>
  <source_title />
  <source_link />
  <comments />
  <references />
  <attachments />
</Content>